package com.xuetang9.fujian.mychat.net;

import com.xuetang9.fujian.mychat.util.SysDTO;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * @author: fujian
 * @description:
 * @date: 2021/5/10 15:35
 * @version: V1.0
 * @package: com.xuetang9.fujian.mychat.net
 **/
public class Server {

    private static List<SocketHandler> handlerList;
    private int port;
    private ServerSocket serverSocket;
    private boolean isRunning;

    public Server(int port) {
        this.port = port;
        this.isRunning = true;
        handlerList = new ArrayList<>();
    }
    public void start(){
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("客户端已开启，监听端口：" + port);
            while (isRunning){
                Socket socket = serverSocket.accept();
                //
                SocketHandler socketHandler = new SocketHandler(socket);
                handlerList.add(socketHandler);
                new Thread(socketHandler).start();
                System.out.println("客户端连接成功：" + socket.getRemoteSocketAddress());
                System.out.println("当前在线人数：" + GetOnLineHandler().size());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /*
     * @Description: 服务端会遍历所有在线的用户，如果找到了接收者，就调用接收对象的send方法
     * @param: dto
     * @param: nickName
     * @return void
     * @author: fujian
     * @date 2021/5/11 21:22
    */
    public static void SendDTO(String nickName,SysDTO dto){
        List<SocketHandler> handlerList = GetOnLineHandler();
        for (SocketHandler handler : handlerList) {
            if (nickName.equals(handler.getCurrentUser().getNickName()));
            try {
                handler.sendDTO(dto);
            } catch (IOException e) {
                e.printStackTrace();
            }
            break;
        }
    }

    public static List<SocketHandler> GetOnLineHandler(){
        // 遍历所有数组元素，如果某个客户端已经是离线状态，就应该从集合中删除这个客户端对象
        ListIterator<SocketHandler> listIt = handlerList.listIterator();
        while (listIt.hasNext()){
            if (listIt.next().getStatus() == SocketHandler.CLOSE){
                listIt.remove();
            }
        }
        return handlerList;
    }

}
